<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="SKU编码" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入SKU编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备货单号" prop="stockOrderNo">
        <el-input
          v-model="queryParams.stockOrderNo"
          placeholder="请输入备货单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属店铺" prop="shopId">
        <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable>
          <el-option
            v-for="item in shopOptions"
            :key="item.shopId"
            :label="item.shopName"
            :value="item.shopId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出库日期">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['stock:outbound:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['stock:outbound:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['stock:outbound:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['stock:outbound:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['stock:outbound:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="outboundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SKU编码" align="center" prop="sku" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="备货单号" align="center" prop="stockOrderNo" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU货号" align="center" prop="skuCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="SKU属性" align="center" prop="skuAttr" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="所属店铺" align="center" prop="shopName" width="120" />
      <el-table-column label="出库数量" align="center" prop="outboundQuantity" width="100">
        <template slot-scope="scope">
          <span style="color: #F56C6C; font-weight: bold;">{{ scope.row.outboundQuantity }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物流费用" align="center" prop="logisticsFee" width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.logisticsFee != null ? '¥' + scope.row.logisticsFee : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出库日期" align="center" prop="outboundDate" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.outboundDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['stock:outbound:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['stock:outbound:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改备货出库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="sku">
              <el-select 
                v-model="form.sku" 
                placeholder="请输入SKU或产品名称搜索" 
                filterable 
                remote
                :remote-method="remoteSearchStock"
                :loading="stockLoading"
                style="width: 100%" 
                :disabled="form.outboundId != null" 
                @change="handleSkuChange"
                @visible-change="handleStockVisibleChange"
                ref="stockSelect"
                popper-class="stock-select-dropdown">
                <el-option
                  v-for="item in stockDetailOptions"
                  :key="item.sku"
                  :label="item.sku + ' - ' + item.productName + ' (库存' + item.remainingStock + '个)'"
                  :value="item.sku"
                  style="height: auto; line-height: normal; padding: 10px 20px;"
                >
                  <div style="line-height: 1.5;">
                    <div style="margin-bottom: 4px;">
                      <span style="font-weight: 500; color: #303133;">{{ item.sku }}</span>
                      <span style="color: #67C23A; font-size: 12px; margin-left: 8px; font-weight: 500;">
                        库存{{ item.remainingStock }}个
                      </span>
                    </div>
                    <div style="font-size: 13px; color: #606266;">
                      {{ item.productName }}
                    </div>
                  </div>
                </el-option>
                <el-option v-if="stockHasMore && !stockLoading" :value="null" disabled style="text-align: center;">
                  <span @click.stop="loadMoreStock" style="color: #409EFF; cursor: pointer;">加载更多...</span>
                </el-option>
                <el-option v-if="stockLoading && stockDetailOptions.length > 0" :value="null" disabled style="text-align: center;">
                  <i class="el-icon-loading"></i> 加载中...
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备货单号" prop="stockOrderNo">
              <el-input v-model="form.stockOrderNo" placeholder="请输入备货单号" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU货号" prop="skuCode">
              <el-input v-model="form.skuCode" placeholder="选择SKU后自动填充" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属店铺" prop="shopId">
              <el-select v-model="form.shopId" placeholder="选择SKU后自动填充" style="width: 100%" disabled>
                <el-option
                  v-for="item in shopOptions"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="出库数量" prop="outboundQuantity">
              <el-input-number v-model="form.outboundQuantity" :min="1" :max="form.maxOutboundQuantity || 999999" placeholder="请输入出库数量" style="width: 100%" />
              <span v-if="form.maxOutboundQuantity" style="color: #909399; font-size: 12px; margin-left: 10px;">
                （剩余库存：{{ form.maxOutboundQuantity }}个）
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物流费用" prop="logisticsFee">
              <el-input-number v-model="form.logisticsFee" :precision="2" :min="0" placeholder="请输入物流费用" style="width: 100%" />
              <span style="color: #909399; font-size: 12px; margin-left: 10px;">（单位：元）</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="出库日期" prop="outboundDate">
              <el-date-picker
                v-model="form.outboundDate"
                type="datetime"
                placeholder="选择出库日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="500px" append-to-body center>
      <div style="padding: 0 20px 20px 20px;">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 15px;">
          <div style="font-size: 13px; line-height: 1.8;">
            <div>• 请确保Excel中包含"所属店铺"列，每行必须填写店铺名称</div>
            <div>• <strong style="color: #E6A23C;">备货单号+SKU为唯一键：相同备货单号和SKU的记录将完全覆盖更新</strong></div>
            <div>• 店铺不存在将自动创建</div>
            <div>• 支持动态表头识别，表头可在前10行任意位置</div>
            <div>• 必填字段：SKU ID、备货单号、所属店铺、备货数量、备货日期</div>
          </div>
        </el-alert>
      </div>
      <div style="display: flex; justify-content: center;">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-error="handleFileError"
          :auto-upload="false"
          drag
          style="text-align: center;"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading" :disabled="upload.isUploading">
          {{ upload.isUploading ? '导入中...' : '确 定' }}
        </el-button>
        <el-button @click="upload.open = false" :disabled="upload.isUploading">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockOutbound, getStockOutbound, delStockOutbound, addStockOutbound, updateStockOutbound, getStockDetail, importStockOutboundTemplate } from "@/api/business/stock"
import { getShopList } from "@/api/system/user"
import { getToken } from "@/utils/auth"

export default {
  name: "StockOutbound",
  computed: {
    stockHasMore() {
      return this.stockDetailOptions.length < this.stockTotal
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 备货出库表格数据
      outboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 店铺选项
      shopOptions: [],
      // 库存明细选项（有库存的SKU）
      stockDetailOptions: [],
      // 库存明细加载状态
      stockLoading: false,
      // 库存明细分页参数
      stockPageNum: 1,
      stockPageSize: 20,
      stockTotal: 0,
      stockSearchKey: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sku: null,
        stockOrderNo: null,
        productName: null,
        shopId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sku: [
          { required: true, message: "SKU编码不能为空", trigger: "change" }
        ],
        stockOrderNo: [
          { required: true, message: "备货单号不能为空", trigger: "blur" }
        ],
        // shopId从库存中自动获取，无需用户填写
        outboundQuantity: [
          { required: true, message: "出库数量不能为空", trigger: "blur" }
        ],
        outboundDate: [
          { required: true, message: "出库日期不能为空", trigger: "change" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/stock/outbound/importData"
      }
    }
  },
  created() {
    this.getList()
    this.getShopOptions()
    // 库存明细改为懒加载，打开下拉框时才加载
  },
  methods: {
    /** 查询备货出库列表 */
    getList() {
      this.loading = true
      listStockOutbound(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.outboundList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取店铺选项 */
    getShopOptions() {
      getShopList().then(response => {
        this.shopOptions = response.data
      })
    },
    /** 获取库存明细选项（支持分页加载） */
    getStockDetailOptions(searchKey = '', isLoadMore = false) {
      this.stockLoading = true
      
      // 如果不是加载更多，重置页码
      if (!isLoadMore) {
        this.stockPageNum = 1
        this.stockSearchKey = searchKey
      }
      
      const params = { 
        pageNum: this.stockPageNum, 
        pageSize: this.stockPageSize
      }
      
      // 如果有搜索关键字，添加搜索条件
      const key = isLoadMore ? this.stockSearchKey : searchKey
      if (key) {
        // 判断是否为数字（可能是SKU）
        if (/^\d+$/.test(key)) {
          params.sku = key
        } else {
          params.productName = key
        }
      }
      
      getStockDetail(params).then(response => {
        // 过滤掉剩余库存为0的记录
        const filteredRows = response.rows.filter(item => item.remainingStock > 0)
        
        // 如果是加载更多，追加数据；否则替换数据
        if (isLoadMore) {
          this.stockDetailOptions = [...this.stockDetailOptions, ...filteredRows]
        } else {
          this.stockDetailOptions = filteredRows
        }
        
        this.stockTotal = response.total
        this.stockLoading = false
      }).catch(() => {
        this.stockLoading = false
      })
    },
    /** 远程搜索库存明细 */
    remoteSearchStock(query) {
      this.getStockDetailOptions(query, false)
    },
    /** 加载更多库存明细 */
    loadMoreStock() {
      if (this.stockLoading || !this.stockHasMore) {
        return
      }
      this.stockPageNum++
      this.getStockDetailOptions(this.stockSearchKey, true)
    },
    /** 下拉框显示/隐藏时的处理 */
    handleStockVisibleChange(visible) {
      if (visible) {
        if (this.stockDetailOptions.length === 0) {
          this.getStockDetailOptions()
        }
        // 延迟重置滚动位置到顶部
        this.$nextTick(() => {
          const selectDropdown = document.querySelector('.stock-select-dropdown .el-select-dropdown__wrap')
          if (selectDropdown) {
            selectDropdown.scrollTop = 0
          }
        })
      }
    },
    /** SKU改变时自动填充产品名称、店铺和可出库数量 */
    handleSkuChange(sku) {
      const stockDetail = this.stockDetailOptions.find(s => s.sku === sku)
      if (stockDetail) {
        this.form.productName = stockDetail.productName
        this.form.shopId = stockDetail.shopId
        this.form.skuCode = stockDetail.skuCode
        this.form.maxOutboundQuantity = stockDetail.remainingStock
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        outboundId: null,
        sku: null,
        stockOrderNo: null,
        productName: null,
        skuCode: null,
        shopId: null,
        outboundQuantity: null,
        logisticsFee: 0,
        outboundDate: null,
        remark: null,
        maxOutboundQuantity: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.outboundId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 重新获取最新的库存明细数据
      this.getStockDetailOptions()
      this.open = true
      this.title = "添加备货出库"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const outboundId = row.outboundId || this.ids
      getStockOutbound(outboundId).then(response => {
        this.form = response.data
        // 修改时，查找对应的库存明细，获取当前可出库数量
        const stockDetail = this.stockDetailOptions.find(s => s.sku === response.data.sku)
        if (stockDetail) {
          // 当前可出库 + 原出库数量（修改时可以改回）
          this.form.maxOutboundQuantity = stockDetail.remainingStock + response.data.outboundQuantity
        } else {
          // 如果找不到库存明细，说明可能库存为0了，只能保持原值
          this.form.maxOutboundQuantity = response.data.outboundQuantity
        }
        this.open = true
        this.title = "修改备货出库"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.outboundId != null) {
            updateStockOutbound(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStockOutbound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const outboundIds = row.outboundId || this.ids
      this.$modal.confirm('删除出库记录后将影响库存计算，是否确认删除？').then(function() {
        return delStockOutbound(outboundIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/stock/outbound/export', {
        ...this.queryParams
      }, `stock_outbound_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "备货出库导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/stock/outbound/importTemplate', {
      }, `备货出库导入模板_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      
      if (response.code === 200) {
        this.$alert("<div style='overflow: auto; text-align: left;'>" + response.msg + "</div>", "导入结果", { 
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: () => {
            this.getList()
          }
        })
      } else {
        this.$alert("<div style='overflow: auto; text-align: left;'>" + response.msg + "</div>", "导入失败", { 
          dangerouslyUseHTMLString: true,
          type: 'error'
        })
      }
    },
    // 文件上传失败处理
    handleFileError(err, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$modal.msgError("导入失败，请重试")
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    }
  }
}
</script>

